using System;
using System.Collections.Generic;
using System.Text;

namespace Acms.DataControls
{
    [System.ComponentModel.Designer(typeof(SiteDataSourceDesigner))]
    [System.Web.UI.ToolboxData("<{0}:SiteDataSource runat=server></{0}:SiteDataSource>")]
    public class SiteDataSource : GenericDataSource<Bll.Site>
    {
        public enum Fields
        {
            Id,
            Name,
            Root,
            ConcurencyId
        }

        protected override Acms.Bll.Site PopulateData(UpdateAction action, System.Collections.IDictionary keys, System.Collections.IDictionary values, System.Collections.IDictionary oldValues)
        {
            Bll.Site tmp = null;
            byte[] concurencyId = null;
            if (action == UpdateAction.Insert)
            {
                tmp = Bll.Site.CreateInstance();
            }
            else
            {
                int id = GetValue<int>(Fields.Id, keys);
                concurencyId = GetValue<byte[]>(Fields.ConcurencyId, keys);
                tmp = Bll.Site.GetById(id);
            }

            if (tmp != null)
            {
                tmp.CheckConcurent(concurencyId);
                if (RequiresUpdate<string>(Fields.Name, values, oldValues))
                {
                    tmp.Name = GetValue<string>(Fields.Name, values);
                }

                if (RequiresUpdate<string>(Fields.Root, values, oldValues))
                {
                    tmp.Root = GetValue<string>(Fields.Root, values);
                }
            }
            return tmp;
        }

        protected override int SaveChanges(Acms.Bll.Site value)
        {
            value.Update();
            return 1;
        }

        protected override void AddInsertedKey(Acms.Bll.Site item, System.Collections.IDictionary values)
        {
            values[Fields.Id.ToString()] = item.Id;
        }
    }

    public class SiteDataSourceDesigner : GenericDataSourceDesigner<Bll.Site>
    {
        protected override Acms.Bll.Site GetDesignTimeItem(int index)
        {
            string[] names = new string[] { "Test Web Site", "Armfelt", "Cool Acms Site", "Cocktails", "My Blog" };
            string[] suffix = new string[] { "com", "co.uk", "net", "org.uk" };
            Random rnd = new Random(index);
            Bll.Site tmp = Bll.Site.CreateInstance();
            tmp.Name = names[rnd.Next(0, names.Length)];
            tmp.Root = string.Format("www.{0}.{1}", tmp.Name.Replace(" ", ""), suffix[rnd.Next(0, suffix.Length - 1)]);
            return tmp;
        }
    }
}
